/*
 * @Description:用户基本信息
 * @Author: wangfuwei
 * @Date: 2020-11-30 17:40:07
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-25 22:48:46
 * @FilePath: /horizon-frontend/src/store/modules/user.js
 */
import Vue from "vue";
import { login, getInfo, logout } from "@/api/user";
import { TOKEN, USER_NAME, NICK_NAME, AVATAR, DEPT, LANGUAGE, PRIMARY_COLOR, COLOR_WEAK } from "@/store/mutation-types";
import { ACCESS_TOKEN } from "@/core/const";

const user = {
  namespaced: true,
  state: {
    token: "", //Token
    username: "", //账号
    nickname: "", //姓名
    avatar: "", //头像
    dept: "", //部门
  },

  mutations: {
    [TOKEN]: (state, token) => {
      state.token = token;
    },
    [USER_NAME]: (state, username) => {
      state.username = username;
    },
    [NICK_NAME]: (state, nickname) => {
      state.nickname = nickname;
    },
    [AVATAR]: (state, avatar) => {
      state.avatar = avatar;
    },
    [DEPT]: (state, dept) => {
      state.dept = dept;
    },
  },

  actions: {
    //用户信息初始化
    __init_user_({ commit }, userInfo = {}) {
      const { username = "", nickname = "", avatar = "", dept = "" } = userInfo;
      commit(USER_NAME, username);
      commit(NICK_NAME, nickname);
      commit(AVATAR, avatar);
      commit(DEPT, dept);
    },

    //系统信息初始化
    __init_app_({ commit }, appInfo = {}) {
      //国际化、主题色、色弱模式
      const { language, primaryColor, colorWeak = false } = appInfo;
      language && commit(`app/${LANGUAGE}`, language, { root: true });
      primaryColor && commit(`app/${PRIMARY_COLOR}`, primaryColor, { root: true });
      commit(`app/${COLOR_WEAK}`, colorWeak, { root: true });
    },

    // 登录
    // eslint-disable-next-line no-empty-pattern
    login({}, userInfo) {
      return (async () => await login(userInfo))();
    },

    // 获取用户信息
    getInfo({ dispatch }) {
      return (async () => {
        const userInfo = await getInfo();
        dispatch("__init_user_", userInfo);
        dispatch("__init_app_", userInfo.meta);
      })();
    },

    // 登出
    logout({ dispatch, commit }) {
      return (async () => {
        await logout();
        Vue.ls.remove(ACCESS_TOKEN);
        commit(TOKEN, "");
        dispatch("__init_app_");
      })();
    },
  },
};

export default user;
